package com.java.comprehensive;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**
 * 微信发送消息
 * @author zhangmingliang
 */
public class WeChatMsgSend {
	private CloseableHttpClient httpClient;
	/**
	 *  用于提交登陆数据
	 */
	private HttpPost httpPost;
	/**
	 *  用于获得登录后的页面
	 */
	private HttpGet httpGet;

	public static final String CONTENT_TYPE = "Content-Type";

	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static Gson gson = new Gson();

	/**
	 * 微信授权请求，GET类型，获取授权响应，用于其他方法截取token
	 * @param Get_Token_Url
	 * @return String 授权响应内容
	 * @throws IOException
	 */
	protected String toAuth(String Get_Token_Url) throws IOException {

		httpClient = HttpClients.createDefault();
		httpGet = new HttpGet(Get_Token_Url);
		CloseableHttpResponse response = httpClient.execute(httpGet);
		String resp;
		try {
			HttpEntity entity = response.getEntity();
			resp = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
		} finally {
			response.close();
		}
		LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
		return resp;
	}

	/**
	 * @Title  创建微信发送请求post实体
	 * charset消息编码    ，contentType消息体内容类型，
	 * url微信消息发送请求地址，data为post数据，token鉴权token
	 * @return String
	 */
	public String post(String charset, String contentType, String url, String data, String token) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		httpPost = new HttpPost(url + token);
		httpPost.setHeader(CONTENT_TYPE, contentType);
		httpPost.setEntity(new StringEntity(data, charset));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		String resp;
		try {
			HttpEntity entity = response.getEntity();
			resp = EntityUtils.toString(entity, charset);
			EntityUtils.consume(entity);
		} finally {
			response.close();
		}
		LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
		return resp;
	}
}
